import { formatGMTDate, toPercent } from '../../../../assets/js/util.js'
import details from './datils.vue'
import echarts from 'echarts'
export default {
    data() {
        return {
            // 默认参数 和 URL
            SRC: '',
            DP: {
                p: '',
                f: ''
            },
            // title
            title: "概况",
            /* 的宽*/
            pageWidth: '100%',
            pickerOptions: {
                shortcuts: [{
                    text: '最近7天',
                    onClick(picker) {
                        const end = new Date();
                        const start = new Date();
                        start.setTime(start.getTime() - 3600 * 1000 * 24 * 7);
                        picker.$emit('pick', [start, end]);
                    }
                }, {
                    text: '最近15天',
                    onClick(picker) {
                        const end = new Date();
                        const start = new Date();
                        start.setTime(start.getTime() - 3600 * 1000 * 24 * 15);
                        picker.$emit('pick', [start, end]);
                    }
                }, {
                    text: '最近30天',
                    onClick(picker) {
                        const end = new Date();
                        const start = new Date();
                        start.setTime(start.getTime() - 3600 * 1000 * 24 * 30);
                        picker.$emit('pick', [start, end]);
                    }
                }]
            },
            date: '',
            // details 展示数据
            datas: [],
            // 默认选择 付费情况 付费率
            activeIndex: '1',
            tableHeader1: [
                { "prop": "title", "label": "指标" },
                { "prop": "activeDeviceRadio", "label": "激活设备" },
                { "prop": "newDeviceRadio", "label": "新增设备" },
                { "prop": "newOnActiveDevcieRadioRadio", "label": "激活-新增转化率" },
                { "prop": "newUserRadio", "label": "新增帐号" },
                { "prop": "activeUserRadio", "label": "活跃帐号" },
                { "prop": "payRadio", "label": "付费金额" },
                { "prop": "payUserRadio", "label": "付费帐号" },
                { "prop": "payOnActiveUserRadioRadio", "label": "活跃付费率" },
                { "prop": "payArpuRadio", "label": "付费ARPU" },
                { "prop": "activeArpuRadio", "label": "活跃ARPU" }
            ],
            tableData1: [],
            tableHeader2: [
                { "prop": "1", "label": "新增账号数" },
                { "prop": "2", "label": "活跃账号数" },
                { "prop": "3", "label": "付费金额" },
                { "prop": "4", "label": "付费账号数" },
                { "prop": "5", "label": "活跃付费率" },
                { "prop": "6", "label": "付费ARPU" }
            ],
            tableData2: [],
            real1: {
                color: ['#2eb398', '#9d79d8', '#79bde9'],
                tooltip: {
                    trigger: 'axis',
                },
                legend: {
                    data: []
                },
                xAxis: {
                    type: 'category',
                    data: []
                },
                yAxis: {},
                grid: {
                    left: '0%',
                    right: '1%',
                    bottom: '15%',
                    containLabel: true
                },
                toolbox: {
                    right: '20',
                    feature: {
                        dataZoom: {
                            yAxisIndex: 'none'
                        },
                        magicType: {
                            type: ['line', 'bar']
                        },
                        restore: {},
                        saveAsImage: {}
                    }
                },
                dataZoom: [{
                    handleIcon: 'M10.7,11.9v-1.3H9.3v1.3c-4.9,0.3-8.8,4.4-8.8,9.4c0,5,3.9,9.1,8.8,9.4v1.3h1.3v-1.3c4.9-0.3,8.8-4.4,8.8-9.4C19.5,16.3,15.6,12.2,10.7,11.9z M13.3,24.4H6.7V23h6.6V24.4z M13.3,19.6H6.7v-1.4h6.6V19.6z',
                    handleSize: '80%',
                    handleStyle: {
                        color: '#fff',
                        shadowBlur: 3,
                        shadowColor: 'rgba(0, 0, 0, 0.6)',
                        shadowOffsetX: 2,
                        shadowOffsetY: 2
                    }
                }],
                series: [{
                    name: 'pcu',
                    type: 'line',
                    smooth: true,
                    symbol: 'circle',
                    data: []
                }, {
                    name: 'acu',
                    type: 'line',
                    smooth: true,
                    data: [],
                    symbol: 'roundRect',
                }, {
                    name: 'acu',
                    type: 'line',
                    smooth: true,
                    data: [],
                    symbol: 'triangle',
                }]
            },
            // 请求参数
            postObj: {
                dstart: '',
                dend: ''
            },
            // hover 注释 指标说明
            introduceHover1: [
                {
                    title: "设备激活",
                    message: "首次启动游戏的设备数（按历史取所有设备的最早启动时间）"
                },
                {
                    title: "新增设备",
                    message: "首次登录游戏的设备数（按历史取所有设备的最早登录时间）"
                },
                {
                    title: "激活新增转化率",
                    message: "首次登录游戏的设备数（按历史取所有设备的最早登录时间）/首次启动游戏的设备数（按历史取所有设备的最早启动时间）"
                },
                {
                    title: "新增账号数",
                    message: "首次登录游戏的账号数（按历史取所有账号的最早登录时间）"
                },
                {
                    title: "活跃账号数",
                    message: "时间粒度内登录游戏的去重账号数"
                },
                {
                    title: "付费金额",
                    message: "时间粒度内的付费总额"
                },
                {
                    title: "付费帐号",
                    message: "时间粒度内的去重付费账号数"
                },
                {
                    title: "活跃付费率",
                    message: "付费账号数/活跃账号数"
                },
                {
                    title: "付费ARPU",
                    message: "付费人数平均消费"
                },
                {
                    title: "活跃ARPU",
                    message: "活跃人数平均消费"
                }
            ],
            introduceHover2: [
                {
                    title: "新增账号数",
                    message: "首次登录游戏的账号数（按历史取所有账号的最早登录时间）"
                },
                {
                    title: "活跃账号数",
                    message: "时间粒度内登录游戏的去重账号数"
                },
                {
                    title: "付费金额",
                    message: "时间粒度内的付费总额"
                },
                {
                    title: "付费帐号",
                    message: "时间粒度内的去重付费账号数"
                },
                {
                    title: "活跃付费率",
                    message: "付费账号数/活跃账号数"
                },
                {
                    title: "付费ARPU",
                    message: "付费人数平均消费"
                }
            ],
            introduceHover3: [
                {
                    title: "PCU",
                    message: "max(1440分钟每分钟的在线去重账号数)"
                },
                {
                    title: "ACU",
                    message: "sum(1440分钟每分钟的在线去重账号数) / 1440"
                }
            ],
            introduceHover4: [
                {
                    title: "DAU-新用户",
                    message: "首次登录游戏的账号数（按历史取所有账号的最早登录时间）"
                },
                {
                    title: "DAU-老用户",
                    message: "时间粒度内登录游戏的去重账号数-首次登录游戏的账号数（按历史取所有账号的最早登录时间）"
                }
            ],
            introduceHover5: [
                {
                    title: "次日留存率",
                    message: "当日新增在次日登录游戏的占当日新增的比例"
                },
                {
                    title: "3日留存率",
                    message: "当日新增在第3日（含新增当日）登录游戏的占当日新增的比例"
                },
                {
                    title: "7日留存率",
                    message: "当日新增在第7日（含新增当日）登录游戏的占当日新增的比例"
                },
            ],
            introduceHover6: [
                {
                    title: "付费金额",
                    message: "时间粒度内的付费总额"
                },
                {
                    title: "付费帐号",
                    message: "时间粒度内的去重付费账号数"
                },
                {
                    title: "活跃付费率",
                    message: "付费账号数/活跃账号数"
                },
                {
                    title: "付费ARPU",
                    message: "付费人数平均消费"
                },
                {
                    title: "活跃ARPU",
                    message: "活跃人数平均消费"
                }
            ],
            introduceHover7: [
                {
                    title: "活跃账号人均在线时长",
                    message: "时间粒度内账号的在线时长 / 活跃账号数 "
                }
            ],
        }
    },
    methods: {
        // 通用 成功 与 失败
        successFun(data) {
            this.$message({
                message: data,
                type: 'success'
            });
        },
        errorFun(data) {
            this.$message.error(data);
        },
        chartsWidth(el) {
            if (document.getElementById(el) !== null) {
                document.getElementById(el).style.width = window.innerWidth - 290 + "px";
            }
        },
        _init() {
            var arr = ['profile1', 'profile2', 'profile3', 'profile4', 'profile5'];
            var arrReals = [this.real1, this.real1, this.real1, this.real1, this.real1];
            for (var x = 0; x < arr.length; x++) {
                this.chartsWidth(arr[x]);
                this[arr[x] + 'Charts'] = echarts.init(document.getElementById(arr[x]));
                this[arr[x] + 'Charts'].setOption(arrReals[x]);
            }
            window.addEventListener('resize', function() {
                for (var i in arr) {
                    this.chartsWidth(arr[i])
                }
                var resizeArr = ['profile1Charts', 'profile2Charts', 'profile3Charts', 'profile4Charts', 'profile5Charts']
                for (var j in resizeArr) {
                    this[resizeArr[j]].resize();
                }
            }.bind(this))
        },
        // 时间改变 得到起始时间和结束时间
        dateChange(val) {
            if (val === undefined) {
                this.errorFun('请选择查看时间！')
            } else {
                var t = val.split(' - ');
                this.postObj.dstart = t[0];
                this.postObj.dend = t[1];
                this.getData(this.postObj);
            }
        },
        // 变成分数
        pencent() {
            var data = this.tableDataAll;
            // 将 一阶登录比 二阶登录比  转换为%比 
            for (var i = 0; i < data.length; i++) {
                for (var j in data[i]) {
                    if (j === 'loginPercent' || j === 'loginPercent2') {
                        data[i][j] = toPercent(data[i][j]);
                    }
                }
            }
            this.tableDataAll = data;
        },
        // 改变表格每行的颜色
        tableRowClassName(row, index) {
            if (index === 0) {
                return 'one-row';
            } else if (index === 1) {
                return 'two-row';
            } else if (index === 2) {
                return 'three-row';
            }
            return '';
        },
        // 获取数据
        getData(data) {
            var that = this;
            var p = new Promise(function(resolve, reject) {
                that.dataTotal = 0;
                that.loading = true;
                that.tableData = [];
                that.tableDataAll = [];
                /*`${that.SRC}bi/overviewReport/search.do`,  {
                		params: data
                	}*/
                /*`${that.SRC}data/get.do?p=${that.DP.p}&f=${that.DP.f}&a=search`, {
                	params: {'ps':`date=${data.date}&cdate=${data.cdate}&platformid=${data.platformid}&channelid=${data.channelid}&serverid=${data.serverid}`}
                }*/
                /*dstart: '',
                dend: ''*/
                that.$http.jsonp(`${that.SRC}data/get.do?p=${that.DP.p}&f=${that.DP.f}&a=search`, {
                    params: { 'ps': `dstart=${data.dstart}&dend=${data.dend}` }
                }).then(function(res) {
                    resolve(res.body)
                })
            })
            p.then(function(value) {
                that.loading = false;
                var data = JSON.parse(value)
                var d = JSON.parse(data.replace(/\"\{\"/g, '\{\"').replace(/\"\}\"/g, '\"\}'));
                if (parseInt(d["res"]) === 0) {
                    that.tableData1 = d.yesterdayDatas;
                    that.datas = d.datas;
                    that.echartsData(d);
                    that.echartsData2(d['chartUIdata5'])
                    that.pencent();
                } else {
                    that.getErrorMsg(Number(d.res))
                }
            })
        },
        handle(key, keyPath) {
            var setColor = [];
            switch (key) {
                case '1':
                    setColor = ['#66cf97', '#4eb59a', '#349b98'];
                    this.activeChange('pay');
                    break;
                case '2':
                    setColor = ['#84ebd8', '#7fd2e2', '#7abde8'];
                    this.activeChange('payUser');
                    break;
                case '3':
                    setColor = ['#b8cff1', '#a99ce4', '#a07cdc'];
                    this.activeChange('payRadio');
                    break;
                case '4':
                    setColor = ['#b8cff1', '#7fd2e2', '#a07cdc'];
                    this.activeChange('payArpu');
                    break;
            }
            this.profile4Charts.setOption({
                series: [{
                    itemStyle: {
                        normal: {
                            color: new echarts.graphic.LinearGradient(
                                0, 0, 0, 1, [
                                    { offset: 0, color: setColor[0] },
                                    { offset: 0.33, color: setColor[1] },
                                    { offset: 0.66, color: setColor[2] },
                                    { offset: 1, color: setColor[0] }
                                ]
                            )
                        },
                        emphasis: {
                            color: new echarts.graphic.LinearGradient(
                                0, 0, 0, 1, [
                                    { offset: 0, color: setColor[0] },
                                    { offset: 0.4, color: setColor[2] },
                                    { offset: 0.7, color: setColor[1] },
                                    { offset: 1, color: setColor[0] }
                                ]
                            )
                        }
                    },
                }]
            });
        },
        // pcu acu pcu_acu 平均在线时长  顶部
        activeChange(url) {
            /*`${that.SRC}data/get.do?p=${that.DP.p}&f=${that.DP.f}&a=onTabChange`,{
            		params:{'ps': `dstart=${this.postObj.dstart}&dend=${this.postObj.dend}&tabType=${url}`}
            	}

            	onTabChange*/
            this.$http.jsonp(`${this.SRC}data/get.do?p=${this.DP.p}&f=${this.DP.f}&a=onTabChange`, {
                params: { 'ps': `dstart=${this.postObj.dstart}&dend=${this.postObj.dend}&tabType=${url}` }
            }).then(function(res) {
                var data = JSON.parse(res.body);
                var d = JSON.parse(data.replace(/\"\{\"/g, '\{\"').replace(/\"\}\"/g, '\"\}'));
                if (d.res === "0") {
                    this.echartsData2(d.chartUIdata5);
                } else {
                    this.errorFun(d['msg']);
                }
            })
        },
        // 改变表数据
        echartsData(d) {
            this.realLoadShow = false;
            // 在线趋势
            if (d.chartUIdata1.length === 0) {
                var data = {
                    "columnkeys": [],
                    "names": [],
                    "data": [
                        []
                    ]
                }
            } else {
                var data = d['chartUIdata1']['jsonStr'];
            }
            this.profile1Charts.setOption({
                legend: {
                    data: data['names']
                },
                xAxis: {
                    data: data.columnkeys
                },
                series: [{
                        name: data.names[0],
                        data: data.data[0]
                    },
                    {
                        name: data.names[1],
                        data: data.data[1]
                    }
                ]
            });

            // 活跃情况
            if (d.chartUIdata3.length === 0) {
                var data2 = {
                    "columnkeys": [],
                    "names": [],
                    "data": [
                        []
                    ]
                }
            } else {
                var data2 = d['chartUIdata3']['jsonStr'];
            }
            this.profile2Charts.setOption({
                tooltip: {
                    formatter: function(a) {
                        return `DAU-总数：${a[0].value+a[1].value}
						</br>
						DAU-老用户：${a[1].value}
						</br>
						DAU-新用户：${a[0].value}`;
                    }
                },
                toolbox: {
                    feature: {
                        magicType: {
                            type: ['stack', 'tiled', 'line', 'bar']
                        },
                    }
                },
                legend: {
                    data: data2['names']
                },
                xAxis: {
                    data: data2.columnkeys
                },
                series: [{
                        type: 'bar',
                        stack: '总量',
                        barWidth: '60px',
                        name: data2.names[0],
                        data: data2.data[0],
                        itemStyle: {
                            normal: {
                                label: {
                                    show: true,
                                    textStyle: {
                                        color: '#fff'
                                    }
                                }
                            }
                        },
                    },
                    {
                        type: 'bar',
                        stack: '总量',
                        barWidth: '40px',
                        name: data2.names[1],
                        data: data2.data[1],
                        itemStyle: {
                            normal: {
                                label: {
                                    show: true,
                                    textStyle: {
                                        color: '#fff'
                                    }
                                }
                            }
                        },
                    }
                ]
            });

            // 留存情况
            if (d.chartUIdata2.length === 0) {
                var data3 = {
                    "columnkeys": [],
                    "names": [],
                    "data": [
                        []
                    ]
                }
            } else {
                var data3 = d['chartUIdata2']['jsonStr'];
            }
            this.profile3Charts.setOption({
                legend: {
                    data: data3['names']
                },
                xAxis: {
                    data: data3.columnkeys
                },
                series: [{
                        name: data3.names[0],
                        data: data3.data[0]
                    },
                    {
                        name: data3.names[1],
                        data: data3.data[1]
                    },
                    {
                        name: data3.names[2],
                        data: data3.data[2]
                    }
                ]
            });

            // 游戏时长（m）
            if (d.chartUIdata4.length === 0) {
                var data4 = {
                    "columnkeys": [],
                    "names": [],
                    "data": [
                        []
                    ]
                }
            } else {
                var data4 = d['chartUIdata4']['jsonStr'];
            }
            this.profile5Charts.setOption({
                legend: {
                    data: data4['names']
                },
                xAxis: {
                    data: data4.columnkeys
                },
                series: [{
                    name: data4.names[0],
                    data: data4.data[0]
                }]
            });
        },
        echartsData2(d) {
            // 付费情况
            if (d === undefined) {
                var data = {
                    "columnkeys": [],
                    "names": [],
                    "data": [
                        []
                    ]
                }
            } else {
                var data = d['jsonStr'];
            }
            this.profile4Charts.setOption({
                legend: {
                    data: data['names']
                },
                xAxis: {
                    data: data.columnkeys
                },
                series: [{
                        name: data.names[0],
                        data: data.data[0]
                    },
                    {
                        name: data.names[1],
                        data: data.data[1]
                    }
                ]
            });
        },
    },
    components: {
        'v-details': details
    },
    mounted() {
        // 初始化URL
        this.SRC = this.$store.getters.src;
        this.DP.p = localStorage.getItem('ZULONGBIPROJECTID');
        this.DP.f = localStorage.getItem('ZULONGBIPAGEID');
        this.date = [new Date(new Date().getTime() - 16 * 86400000), new Date(new Date().getTime() - 86400000)];
        this.postObj.dstart = formatGMTDate(new Date().getTime() - 86400000 * 16, true);
        this.postObj.dend = formatGMTDate(new Date().getTime() - 86400000, true);
        // 实时数据
        this._init();
        this.getData(this.postObj);
        /*this.echartsData();*/
    }
}